package com.sca.order.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sca.order.annotation.RequireToken;
import com.sca.order.entity.api.BaseResult;
import com.sca.order.entity.enums.ResultEnum;
import com.sca.order.utils.JwtUtil;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author liuxianfei
 * @since 2020/11/3 10:04
 */
@Setter
@Getter
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        RequireToken requireToken = AnnotationUtils.findAnnotation(method, RequireToken.class);
        if (requireToken != null && requireToken.required()) {
            if (!JwtUtil.validateToken(request)) {
                BaseResult<?> result = new BaseResult<>(ResultEnum.ERR_TOKEN_ERROR);
                objectMapper.writeValue(response.getOutputStream(), result);
                response.getOutputStream().flush();
                return false;
            }
        }
        return true;
    }

}
